/**
 * PromptBuilder - 提示词构建器
 * 基于 Augment Code 的动态提示词生成机制
 */

import { 
  ConversationContext, 
  PromptConfig, 
  CodeContext, 
  AgentMemory, 
  Turn, 
  ChatMode,
  NodeType,
  ToolType 
} from './types';

export class PromptBuilder {
  private defaultConfig: PromptConfig = {
    systemPrompt: 'You are Augment Agent, an AI coding assistant.',
    includeCodeContext: true,
    includeMemories: true,
    includeToolHistory: true,
    maxContextLength: 8000,
    temperature: 0.7,
    maxTokens: 4000,
  };

  constructor(private config: Partial<PromptConfig> = {}) {
    this.defaultConfig = { ...this.defaultConfig, ...config };
  }

  /**
   * 构建完整的提示词
   */
  buildPrompt(
    userMessage: string,
    context: ConversationContext,
    config?: Partial<PromptConfig>
  ): string {
    const finalConfig = { ...this.defaultConfig, ...config };
    
    const sections: string[] = [];
    
    // 1. 系统提示词
    sections.push(this.buildSystemPrompt(context, finalConfig));
    
    // 2. 代码上下文
    if (finalConfig.includeCodeContext && context.codeContext) {
      const codeSection = this.buildCodeContextSection(context.codeContext);
      if (codeSection) sections.push(codeSection);
    }
    
    // 3. 记忆上下文
    if (finalConfig.includeMemories && context.memories.length > 0) {
      const memorySection = this.buildMemorySection(context.memories);
      if (memorySection) sections.push(memorySection);
    }
    
    // 4. 工具历史
    if (finalConfig.includeToolHistory) {
      const toolSection = this.buildToolHistorySection(context.turns);
      if (toolSection) sections.push(toolSection);
    }
    
    // 5. 对话历史
    const historySection = this.buildConversationHistory(context.turns);
    if (historySection) sections.push(historySection);
    
    // 6. 当前用户消息
    sections.push(`Human: ${userMessage}`);
    sections.push('Assistant:');
    
    const fullPrompt = sections.join('\n\n');
    
    // 检查长度限制
    return this.truncateIfNeeded(fullPrompt, finalConfig.maxContextLength || 100);
  }

  /**
   * 构建系统提示词
   */
  private buildSystemPrompt(context: ConversationContext, config: PromptConfig): string {
    let systemPrompt = config.systemPrompt || ``;
    
    // 根据聊天模式调整系统提示词
    switch (context.mode) {
      case ChatMode.AGENT:
        systemPrompt += '\n\nYou are in Agent mode. You can use tools to help with coding tasks, file operations, and code analysis.';
        break;
      case ChatMode.REMOTE_AGENT:
        systemPrompt += '\n\nYou are a Remote Agent working in an isolated environment. You can perform complex multi-step tasks.';
        break;
      case ChatMode.MEMORIES:
        systemPrompt += '\n\nYou have access to conversation memories to provide contextual assistance.';
        break;
    }
    
    // 添加可用工具信息
    if (context.activeTools.length > 0) {
      systemPrompt += `\n\nAvailable tools: ${context.activeTools.join(', ')}`;
    }
    
    return systemPrompt;
  }

  /**
   * 构建代码上下文部分
   */
  private buildCodeContextSection(codeContext: CodeContext): string | null {
    const sections: string[] = [];
    
    if (codeContext.currentFile) {
      sections.push(`Current file: ${codeContext.currentFile}`);
    }
    
    if (codeContext.selectedCode) {
      sections.push(`Selected code:\n\`\`\`\n${codeContext.selectedCode}\n\`\`\``);
    }
    
    if (codeContext.gitBranch) {
      sections.push(`Git branch: ${codeContext.gitBranch}`);
    }
    
    if (codeContext.recentChanges && codeContext.recentChanges.length > 0) {
      sections.push(`Recent changes:\n${codeContext.recentChanges.slice(0, 5).join('\n')}`);
    }
    
    if (codeContext.workspaceFiles.length > 0) {
      const fileList = codeContext.workspaceFiles.slice(0, 20).join('\n');
      sections.push(`Workspace files:\n${fileList}`);
    }
    
    return sections.length > 0 ? `# Code Context\n${sections.join('\n\n')}` : null;
  }

  /**
   * 构建记忆部分
   */
  private buildMemorySection(memories: AgentMemory[]): string | null {
    const acceptedMemories = memories
      .filter(m => m.state === 'accepted')
      .slice(0, 10); // 限制记忆数量
    
    if (acceptedMemories.length === 0) return null;
    
    const memoryTexts = acceptedMemories.map(memory => 
      `- ${memory.content} (from ${memory.source})`
    );
    
    return `# Relevant Memories\n${memoryTexts.join('\n')}`;
  }

  /**
   * 构建工具历史部分
   */
  private buildToolHistorySection(turns: Turn[]): string | null {
    const toolUsages: string[] = [];
    
    // 获取最近的工具使用
    const recentTurns = turns.slice(-5);
    
    for (const turn of recentTurns) {
      const toolNodes = turn.nodes.filter(node => 
        node.type === NodeType.ToolUse || node.type === NodeType.ToolUseStart
      );
      
      for (const node of toolNodes) {
        if (node.type === NodeType.ToolUse) {
          const toolNode = node as any;
          toolUsages.push(`${toolNode.tool}: ${JSON.stringify(toolNode.input)}`);
        }
      }
    }
    
    return toolUsages.length > 0 
      ? `# Recent Tool Usage\n${toolUsages.slice(-10).join('\n')}` 
      : null;
  }

  /**
   * 构建对话历史
   */
  private buildConversationHistory(turns: Turn[]): string | null {
    if (turns.length === 0) return null;
    
    const historyLines: string[] = [];
    const recentTurns = turns.slice(-5); // 只包含最近5轮对话
    
    for (const turn of recentTurns) {
      historyLines.push(`Human: ${turn.requestMessage}`);
      
      // 提取响应文本
      const responseTexts = turn.nodes
        .filter(node => node.type === NodeType.RawResponse)
        .map(node => (node as any).text)
        .join('');
      
      if (responseTexts) {
        historyLines.push(`Assistant: ${responseTexts}`);
      }
    }
    
    return historyLines.length > 0 
      ? `# Conversation History\n${historyLines.join('\n\n')}` 
      : null;
  }

  /**
   * 截断过长的提示词
   */
  private truncateIfNeeded(prompt: string, maxLength: number): string {
    if (prompt.length <= maxLength) return prompt;
    
    // 简单的截断策略：保留开头和结尾，移除中间部分
    const keepStart = Math.floor(maxLength * 0.3);
    const keepEnd = Math.floor(maxLength * 0.3);
    const start = prompt.substring(0, keepStart);
    const end = prompt.substring(prompt.length - keepEnd);
    
    return `${start}\n\n[... content truncated ...]\n\n${end}`;
  }

  /**
   * 生成建议问题的提示词
   */
  buildSuggestedQuestionsPrompt(turns: Turn[]): string {
    const lastTurn = turns[turns.length - 1];
    if (!lastTurn) return '';
    
    return `Based on the conversation, generate 3-5 relevant follow-up questions that would help the user continue the discussion. Focus on:
1. Clarifying requirements
2. Exploring implementation details  
3. Suggesting improvements
4. Identifying potential issues

Last exchange:
Human: ${lastTurn.requestMessage}
Assistant: [previous response]

Generate questions as a simple list, one per line.`;
  }

  /**
   * 更新默认配置
   */
  updateConfig(config: Partial<PromptConfig>): void {
    this.defaultConfig = { ...this.defaultConfig, ...config };
  }

  /**
   * 获取当前配置
   */
  getConfig(): PromptConfig {
    return { ...this.defaultConfig };
  }
}
